<?php

namespace App\Console;

use App\Events\OrderDeleted;
use App\Exceptions\OperateFailedException;
use App\Models\Order;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        //过期自动软删除
        $schedule->call(function (){
            $orders = Order::where('status',Order::ORDER_STATUS_PUBLISHED);
            if (isset($orders)){
                foreach ($orders as $order){
                    if ($order->ddl == date('Y-m-d H:00:00',time())){
                        DB::beginTransaction();
                        try{
                            $order->delete();
                            event(new OrderDeleted($order));
                            DB::commit();
                        }catch (\Exception $exception){
                            DB::rollBack();
                            Log::error($exception->getMessage());
                            throw new OperateFailedException();
                        }
                    }
                }
            }
        })->hourly();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}
